<template>
  <div class="department-products-container">
    <div class="header">
      <h3>部门商品管理</h3>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加部门商品
      </el-button>
    </div>

    <div class="search-bar">
      <el-select
        v-model="searchDepartment"
        placeholder="按部门筛选"
        style="width: 200px"
        clearable
        @change="handleSearch"
      >
        <el-option
          v-for="department in departments"
          :key="department.departmentId"
          :label="department.name"
          :value="department.departmentId"
        />
      </el-select>
      <el-select
        v-model="searchProduct"
        placeholder="按商品筛选"
        style="width: 200px; margin-left: 10px"
        clearable
        @change="handleSearch"
      >
        <el-option
          v-for="product in products"
          :key="product.productId"
          :label="product.name"
          :value="product.productId"
        />
      </el-select>
    </div>

    <el-table :data="departmentProducts" style="width: 100%" v-loading="loading">
      <el-table-column prop="departmentName" label="部门名称" width="150" />
      <el-table-column prop="productName" label="商品名称" width="180" />
      <el-table-column prop="price" label="价格" width="120">
        <template #default="{ row }">
          {{ row.price || 0 }} 元
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="数量" width="120" />
      <el-table-column prop="description" label="描述" show-overflow-tooltip />
      <el-table-column prop="model" label="型号" width="120" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加部门商品' : '编辑部门商品'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="部门" prop="departmentId">
          <el-select v-model="form.departmentId" placeholder="请选择部门">
            <el-option
              v-for="department in departments"
              :key="department.departmentId"
              :label="department.name"
              :value="department.departmentId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品" prop="productId">
          <el-select v-model="form.productId" placeholder="请选择商品">
            <el-option
              v-for="product in products"
              :key="product.productId"
              :label="product.name"
              :value="product.productId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="form.price" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="form.quantity" :min="0" :precision="0" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input v-model="form.model" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../api'

const departmentProducts = ref([])
const departments = ref([])
const products = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)

const searchDepartment = ref('')
const searchProduct = ref('')

const form = ref({
  departmentId: '',
  productId: '',
  price: 0,
  quantity: 0,
  description: '',
  model: ''
})

const rules = {
  departmentId: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  productId: [
    { required: true, message: '请选择商品', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', message: '价格必须为数字', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', message: '数量必须为数字', trigger: 'blur' }
  ]
}

const loadData = async () => {
  loading.value = true
  try {
    const [departmentProductsRes, departmentsRes, productsRes] = await Promise.all([
      api.get('/department-products'),
      api.get('/departments'),
      api.get('/products')
    ])
    departmentProducts.value = departmentProductsRes || []
    departments.value = departmentsRes || []
    products.value = productsRes || []
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
    departmentProducts.value = []
    departments.value = []
    products.value = []
  }
  loading.value = false
}

const handleSearch = async () => {
  loading.value = true
  try {
    const response = await api.get('/department-products')
    let filteredData = response || []
    
    if (searchDepartment.value) {
      filteredData = filteredData.filter(item => item.departmentId === searchDepartment.value)
    }
    if (searchProduct.value) {
      filteredData = filteredData.filter(item => item.productId === searchProduct.value)
    }
    
    departmentProducts.value = filteredData
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  }
  loading.value = false
}

const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    departmentId: '',
    productId: '',
    price: 0,
    quantity: 0,
    description: '',
    model: ''
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = {
    departmentId: row.departmentId,
    productId: row.productId,
    price: row.price,
    quantity: row.quantity,
    description: row.description,
    model: row.model
  }
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该部门商品关联吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await api.delete(`/department-products/${row.departmentId}/${row.productId}`)
      ElMessage.success('删除成功')
      loadData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = {
          departmentId: form.value.departmentId,
          productId: form.value.productId,
          price: form.value.price,
          quantity: form.value.quantity,
          description: form.value.description,
          model: form.value.model
        }
        if (dialogType.value === 'add') {
          await api.post('/department-products', data)
          ElMessage.success('添加成功')
        } else {
          await api.put(`/department-products/${form.value.departmentId}/${form.value.productId}`, data)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        loadData()
      } catch (error) {
        const errorMessage = error.response?.data?.message || (dialogType.value === 'add' ? '添加失败' : '更新失败')
        ElMessage.error(errorMessage)
      }
    }
  })
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.department-products-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 